package main

import (
	"log"
	"net/http"
	"time"
)

type MiddleWare struct {

}

// Log: 记录请求所消耗的时间
func (m MiddleWare) LoggingHandler(next http.Handler) http.Handler  {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t1 := time.Now()
		next.ServeHTTP(w, r)
		t2 := time.Now()
		log.Printf("[%s] %q %v", r.Method, r.URL.String(), t2.Sub(t1))
	})
}

// Recover: 恢复panic避免程序crash
func (m MiddleWare) RecoverHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
		defer func() {
			if err := recover(); err != nil {
				log.Printf("REcover from panic: %v", err)
				http.Error(w, http.StatusText(500), 500)
			}
		}()
		next.ServeHTTP(w, r)
	})
}
